OPC Studio User's Guide and Reference
File Provider Model in OPC UA
Client and Subscriber Development > Features > Specialized Client Objects > OPC UA File Transfer > File Provider Model in OPC UA
In This Topic

With the File Provider Model, not only are the operations on file data (contents) generalized, but also the operations on the file system itself, such as navigation between directories and files, creating and deleting files and directories, etc. The File Provider Model allows you to work with OPC UA file system in the same way as with the physical file system, and other file systems for which the file providers are available (such as file providers for embedded resources) from Microsoft or other parties.

See Microsoft documentation, File Providers in ASP.NET Core, for fundamentals of the file provider model. Microsoft's file provider model is read-only (does not allow any changes to files or directories), and lacks some features. OPC Data Client builds on top of the Microsoft's file provider model, adding the missing features, and an ability to modify the files and directories.

For accessing the actual file data, the File Provider uses the Stream abstraction, analogous to API Level 2++, differing only in the methods that you use to obtain the data streams. Once your code has obtained the stream object for a particular OPC UA file, it can work with it as with any other data stream.

This article describes API level 3 for OPC UA file transfer; for an overview of API levels, see File Provider Model in OPC UA.

You may also want to look at OPC UA File Transfers internals in order to understand a bit of what is happening "under the hood".

The features discussed here, or some of them, may not be available in all editions of the product. Check the Product Editions page for differences between the editions. The trial license has all features enabled (and is limited in period for which it provides valid data), but licenses for specific commercial editions may have functionality limitations.
This functionality is not available under (or the text does not apply to) COM development platform.

File provider model interfaces

Objects in the file provider model are accessed through interfaces. There are three main groups of interfaces. First one (a usual starting point) is for access to the file system as a whole - called "file provider". You can obtain "file info" interfaces and "directory contents" interfaces from the file provider, they are the second and the third group. "File info" is for access to individual files, and (to a limited extent) an information about individual directories. "Directory contents" represents the directory, together with its files and sub-directories.

For access to the file system as a whole, or its part, the interfaces below are used; we will refer to them as "file provider" interfaces (and they are implemented by "file provider" objects):

 For access to files and file data, the interfaces below are used; we will refer to them as "file info" interfaces (and they are implemented by "file info" objects):

 For access to directories in the file system, the interfaces: below are used; we will refer to them as "directory contents" interfaces (and they are implemented by "directory contents" objects):

Since the interfaces with the digit "2" at the end of their name are simply improvements over the interfaces without the "2", in most cases you can simply use the interfaces with the "2" suffix instead. In theory, you could also extend this reasoning further, and since the interfaces with "Writable" in their name only add writable file system functionality to the interfaces with "2" at the end of their name, you could just use the interfaces with "Writable" in their name wherever possible, and not bother with the other interfaces. This approach would work, but we recommend that you only use the interfaces with "Writable" in their name only if their additional methods are really needed, and do not "pull in" the unnecessary functionality in this way. In addition, there are slight differences in behavior for non-existent objects, etc.

If you need to make OPC UA File Transfer operations and do not want to write code, or if you just need to experiment with it, you can use the OpcCmd Utility, which has full support for OPC UA File Transfer. For more information, see Using OpcCmd Utility for OPC UA File Transfer. What's particularly worth noting is that there commands available for OPC UA File Transfer in the OpcCmd utility that are based on the file provider model, and therefore the information about how the file provider model works in the code API is also relevant for and usable with the OpcCmd utility. For example, the "fileInfo" command in OpcCmd provides functionality that corresponds to the IWritableFileInfo Interface, and the "directoryContents" command provides functionality that corresponds to the IWritableDirectoryContents Interface.

Error model

Microsoft does not document the behavior of the interfaces used in the file provider model well (or not at all). This has consequences on anything that implements, extends or consumes these interfaces. We have tried to adopt an error behavior similar to what Microsoft does in their own file providers, by making experiments and carefully studying the available source code.

Many error conditions are indicated by throwing an IOException or an exception derived from it, however that is not the full story. The exceptions thrown by methods in the file provider model are (derived exception are allowed too, of course):

Contrary to common practice, accessing object properties can throw exceptions as well.

Note that operations that just obtain one of the file provider model interfaces do not fail. Instead of failing, they will return an interface that represents an "invalid" or "not found" object, and behaves appropriately. This is intentional, and in some cases, is the normal way of operation. For example, you can obtain a "directory contents" object for a directory that does not yet exist, and then call the Create Method to create the directory. Similarly, you can obtain a "file info" object for a file that does not yet exist, and then call the CreateWriteStream Method to create the file and start writing into it.

The file provider model does not have a good way of reporting directory enumeration failures (the objects that could not be enumerate will simply be missing from the sequence), and some property-get failures.

Obtaining file provider objects

How the objects in the file provider model are obtained depends on their type. Our concern here are only the objects that implement the file provider model for OPC UA File Transfer, so that's what we are going to describe below.

If you already have any of the "file provider" interfaces, the "file info" and "directory contents" interfaces can be obtained from them. In addition, OPC Data Client allows you to obtain the "file info" and "directory contents" objects directly, without having to start with a "file provider" object. This may come handy (and is, in fact, necessary if you are dealing with OPC UA files that are not part of a file system), but the downside is that you may not be able to reach "outside" of the capabilities of the object you started with. For example, if you start with the "file info" object, then just by using its interfaces, you cannot make any operations on its containing directory. If you, however, start with the "file provider", you will always have a way of reaching anything that is in or under the directory where the file provider is "rooted".

In order to directly obtain file provider objects, you use methods in the IEasyUAFileTransferExtension Class. They are:

All above methods reside "outside" the file provider model, i.e. they provide entry points into the model. At least one of them must eventually be called, if you want to start the objects in the file provider model. Note that there are no methods for obtaining the interfaces without "2" at the end of their name; this is not a problem, as the interfaces with the "2" suffix provide all functionality of their base interfaces, and some more.

Indirectly, further file provider objects can then be obtained by various ways; some of them are listed below.

All above methods reside "inside" the file provider model, and are the same regardless of the type of the file provider (there is nothing OPC UA-specific about them, and OPC UA concepts such as node Ids are no longer "visible").

The code showing how the file provider objects can be obtained can be seen in all code examples in this article.

Getting information about files and directories

Information about a file or directory can be obtained by getting properties of the corresponding "file info" object.

The example below shows how to get OPC UA file properties (such as its size or last modified time), using the file provider model.

// Shows how to get OPC UA file properties (such as its size or last modified time), using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._FileInfo2
{
    class Properties
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            UAEndpointDescriptor endpointDescriptor = "opc.tcp://localhost:48030";

            // A node that represents an instance of OPC UA FileType object.
            UANodeDescriptor fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile";
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting file info...");
            IFileInfo2 fileInfo2 = fileTransferClient.GetFileInfo2(endpointDescriptor, fileNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Get properties of a specified file.
            Console.WriteLine("Getting file properties...");
            try
            {
                // Display result
                Console.WriteLine();
                Console.WriteLine($"Exists: {fileInfo2.Exists}");
                Console.WriteLine($"IsDirectory: {fileInfo2.IsDirectory}");
                Console.WriteLine($"LastModified: {fileInfo2.LastModified}");
                Console.WriteLine($"Length: {fileInfo2.Length}");
                Console.WriteLine($"Name: {fileInfo2.Name}");
                Console.WriteLine($"PhysicalPath: {fileInfo2.PhysicalPath}");
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine();
            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to get OPC UA file properties (such as its size or last modified time), using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.FileTransfer import *
from OpcLabs.EasyOpc.UA.Navigation import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')

# A node that represents an instance of OPC UA FileType object.
fileNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile')

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

print('Getting file info......')
fileInfo2 = IEasyUAFileTransferExtension.GetFileInfo2(fileTransferClient,
                                                      endpointDescriptor,
                                                      UANamedNodeDescriptor(fileNodeDescriptor))
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Get properties of a specified file.
try:
    # Display result.
    print()
    print('Exists: ', fileInfo2.Exists, sep='')
    print('IsDirectory: ', fileInfo2.IsDirectory, sep='')
    print('LastModified: ', fileInfo2.LastModified, sep='')
    print('Length: ', fileInfo2.Length, sep='')
    print('Name: ', fileInfo2.Name, sep='')
    print('PhysicalPath: ', fileInfo2.PhysicalPath, sep='')

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

print()
print('Finished.')
' Shows how to get OPC UA file properties (such as its size or last modified time), using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._FileInfo2

    Friend Class Properties

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor = "opc.tcp://localhost:48030"

            ' A node that represents an instance of OPC UA FileType object.
            Dim fileNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting file info...")
            Dim fileInfo2 As IFileInfo2 =
                fileTransferClient.GetFileInfo2(endpointDescriptor, fileNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Get properties of a specified file.
            Console.WriteLine("Getting file properties...")
            Try
                ' Display result
                Console.WriteLine()
                Console.WriteLine($"Exists: {fileInfo2.Exists}")
                Console.WriteLine($"IsDirectory: {fileInfo2.IsDirectory}")
                Console.WriteLine($"LastModified: {fileInfo2.LastModified}")
                Console.WriteLine($"Length: {fileInfo2.Length}")
                Console.WriteLine($"Name: {fileInfo2.Name}")
                Console.WriteLine($"PhysicalPath: {fileInfo2.PhysicalPath}")

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine()
            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

The "directory contents" objects, by themselves, provide a sequence (enumerable) of "file info" objects, representing the files and sub-directories contained in the directory.

The example below shows how to browse for OPC UA files and directories, using the file provider model.

// Shows how to browse for OPC UA files and directories, using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.Extensions;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._DirectoryContents2
{
    class Enumerate
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            var endpointDescriptor = new UAEndpointDescriptor("opc.tcp://localhost:48030")
                .WithUserNameIdentity("john", "master");

            // A node that represents an OPC UA file system (a root directory).
            UANodeDescriptor fileSystemNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem";

            // Create a random number generator - will be used for file/directory names.
            var random = new Random();
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting writable file provider...");
            IWritableFileProvider writableFileProvider =
                fileTransferClient.GetWritableFileProvider(endpointDescriptor, fileSystemNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Create two files, and then browse the directory that contains them.
            try
            {
                string fileName1 = "MyFile1-" + random.Next();
                Console.WriteLine($"Creating first file, '{fileName1}'...");
                IWritableFileInfo writableFileInfo1 = writableFileProvider.GetWritableFileInfo(fileName1);
                writableFileInfo1.WriteAllBytes(Array.Empty<byte>());

                string fileName2 = "MyFile2-" + random.Next();
                Console.WriteLine($"Creating second file, '{fileName2}'...");
                IWritableFileInfo writableFileInfo2 = writableFileProvider.GetWritableFileInfo(fileName2);
                writableFileInfo2.WriteAllBytes(Array.Empty<byte>());

                Console.WriteLine("Browsing for files...");
                IDirectoryContents2 directoryContents2 = writableFileProvider.GetDirectoryContents2(null);
                foreach (IFileInfo2 fileInfo2 in directoryContents2)
                    Console.WriteLine(fileInfo2);
                // You can distinguish between files and directories using the IFileInfo.IsDirectory property.
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to browse for OPC UA files and directories, using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc
import random

# Import .NET namespaces.
from System import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.Extensions import *
from OpcLabs.EasyOpc.UA.FileTransfer import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')
endpointDescriptor = UAEndpointDescriptorExtension.WithUserNameIdentity(endpointDescriptor,'john', 'master')

# A node that represents an OPC UA file system (a root directory).
fileSystemNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem')

# Create a random number generator - will be used for file/directory names.
random = random.Random()

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

# Prevent prompt to trust the server certificate (INSECURE, used just for smooth example flow).
EasyUAClient.SharedParameters.EngineParameters.CertificateAcceptancePolicy.TrustEndpointUrlString(
    endpointDescriptor.UrlString)

print('Getting writable file provider...')
writableFileProvider = IEasyUAFileTransferExtension.GetWritableFileProvider(fileTransferClient,
                                                                            endpointDescriptor,
                                                                            fileSystemNodeDescriptor)
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Create two files, and then browse the directory that contains them.
try:
    fileName1 = 'MyFile1-' + str(random.randint(0, 999_999_999))
    print("Creating first file, '", fileName1, "'...", sep='')
    writableFileInfo1 = writableFileProvider.GetWritableFileInfo(fileName1)
    IWritableFileInfoExtension.WriteAllBytes(writableFileInfo1, Array.Empty[Byte]())

    fileName2 = 'MyFile2-' + str(random.randint(0, 999_999_999))
    print("Creating second file, '", fileName2, "'...", sep='')
    writableFileInfo2 = writableFileProvider.GetWritableFileInfo(fileName2)
    IWritableFileInfoExtension.WriteAllBytes(writableFileInfo2, Array.Empty[Byte]())

    print('Browsing for files...')
    directoryContents2 = writableFileProvider.GetDirectoryContents2(None)
    for fileInfo2 in directoryContents2:
        print(fileInfo2)
    # You can distinguish between files and directories using the IFileInfo.IsDirectory property.

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

print()
print('Finished.')
' Shows how to browse for OPC UA files and directories, using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.Extensions
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._DirectoryContents2

    Friend Class Enumerate

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor =
                New UAEndpointDescriptor("opc.tcp://localhost:48030") _
                .WithUserNameIdentity("john", "master")

            ' A node that represents an OPC UA file system (a root directory).
            Dim fileSystemNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem"

            ' Create a random number generator - will be used for file/directory names.
            Dim random = New Random

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting writable file provider...")
            Dim writableFileProvider As IWritableFileProvider =
                fileTransferClient.GetWritableFileProvider(endpointDescriptor, fileSystemNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Create two files, and then browse the directory that contains them.
            Try
                Dim fileName1 As String = "MyFile1-" & random.Next()
                Console.WriteLine($"Creating first file, '{fileName1}'...")
                Dim writableFileInfo1 As IWritableFileInfo = writableFileProvider.GetWritableFileInfo(fileName1)
                writableFileInfo1.WriteAllBytes(Array.Empty(Of Byte))

                Dim fileName2 As String = "MyFile2-" & random.Next()
                Console.WriteLine($"Creating second file, '{fileName2}'...")
                Dim writableFileInfo2 As IWritableFileInfo = writableFileProvider.GetWritableFileInfo(fileName2)
                writableFileInfo2.WriteAllBytes(Array.Empty(Of Byte))

                Console.WriteLine("Browsing for files...")
                Dim directoryContents2 As IDirectoryContents2 = writableFileProvider.GetDirectoryContents2(Nothing)

                For Each fileInfo2 As IFileInfo2 In directoryContents2
                    Console.WriteLine(fileInfo2)
                Next fileInfo2
                ' You can distinguish between files and directories using the IFileInfo.IsDirectory property.

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

Other (extension) methods in this group, possibly not used in the above examples, include:

Reading and writing file data

The file provider model uses .NET streams (Stream Class) for file reading, writing and positioning. In part, the information in the OPC UA File Streams article also applies.

Reading

In order to read data from an existing file in the file provider model, start by calling the CreateReadStream Method on the "file info" object. This method returns a stream object that can subsequently be used to access the file data for reading. Eventually, the stream object should be disposed of using the IDisposable.Dispose Method.

The example below shows how to read different sections from an OPC UA file, using the file provider model.

// Shows how to read different sections from an OPC UA file, using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using System.IO;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._FileInfo2
{
    class ReadAndSeek
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            UAEndpointDescriptor endpointDescriptor = "opc.tcp://localhost:48030";

            // A node that represents an instance of OPC UA FileType object.
            UANodeDescriptor fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile";
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting file info...");
            IFileInfo2 fileInfo2 = fileTransferClient.GetFileInfo2(endpointDescriptor, fileNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Open the file, read two separate sections of it, and close it.
            try
            {
                Console.WriteLine("Opening file...");
                using (Stream stream = fileInfo2.CreateReadStream())
                {
                    Console.WriteLine("Reading first section of a stream...");
                    var buffer1 = new byte[16];
                    int bytesRead1 = stream.Read(buffer1, 0, buffer1.Length);
                    Console.WriteLine($"{bytesRead1} bytes read, buffer: {BitConverter.ToString(buffer1)}");

                    Console.WriteLine("Reading second section of a stream...");
                    var buffer2 = new byte[10];
                    int bytesRead2 = stream.Read(buffer2, 0, buffer2.Length);
                    Console.WriteLine($"{bytesRead2} bytes read, buffer: {BitConverter.ToString(buffer2)}");

                    Console.WriteLine("Seeking...");
                    stream.Seek(100, SeekOrigin.Begin);

                    Console.WriteLine("Reading third section of a stream...");
                    var buffer3 = new byte[20];
                    int bytesRead3 = stream.Read(buffer3, 0, buffer3.Length);
                    Console.WriteLine($"{bytesRead3} bytes read, buffer: {BitConverter.ToString(buffer3)}");
                }
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to read different sections from an OPC UA file, using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from System import *
from System.IO import *
from System.Text import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.FileTransfer import *
from OpcLabs.EasyOpc.UA.Navigation import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')

# A node that represents an instance of OPC UA FileType object.
fileNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile')

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

print('Getting file info......')
fileInfo2 = IEasyUAFileTransferExtension.GetFileInfo2(fileTransferClient,
                                                      endpointDescriptor,
                                                      UANamedNodeDescriptor(fileNodeDescriptor))
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Open the file, read two separate sections of it, and close it.
stream = None
try:
    print('Opening file...')
    stream = fileInfo2.CreateReadStream()

    print('Reading first section of a stream...')
    buffer1 = Array.CreateInstance(Byte, 16)
    bytesRead1, _ = stream.Read(buffer1, 0, buffer1.Length)
    print(bytesRead1, ' bytes read, buffer: ', BitConverter.ToString(buffer1), sep='')

    print('Reading second section of a stream...')
    buffer2 = Array.CreateInstance(Byte, 10)
    bytesRead2, _ = stream.Read(buffer2, 0, buffer2.Length)
    print(bytesRead2, ' bytes read, buffer: ', BitConverter.ToString(buffer2), sep='')

    print('Seeking...')
    stream.Seek(100, SeekOrigin.Begin)

    print('Reading third section of a stream...')
    buffer3 = Array.CreateInstance(Byte, 20)
    bytesRead3, _ = stream.Read(buffer3, 0, buffer3.Length)
    print(bytesRead3, ' bytes read, buffer: ', BitConverter.ToString(buffer3), sep='')

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

finally:
    stream and stream.Dispose()

print()
print('Finished.')
' Shows how to read different sections from an OPC UA file, using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports System.IO
Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._FileInfo2

    Friend Class ReadAndSeek

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor = "opc.tcp://localhost:48030"

            ' A node that represents an instance of OPC UA FileType object.
            Dim fileNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting file info...")
            Dim fileInfo2 As IFileInfo2 =
                fileTransferClient.GetFileInfo2(endpointDescriptor, fileNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Open the file, read two separate sections of it, and close it.
            Try
                Console.WriteLine("Opening file...")
                Using stream As Stream = fileInfo2.CreateReadStream()
                    Console.WriteLine("Reading first section of a stream...")
                    Dim buffer1(16 - 1) As Byte
                    Dim bytesRead1 As Integer = stream.Read(buffer1, 0, buffer1.Length)
                    Console.WriteLine($"{bytesRead1} bytes read, buffer: {BitConverter.ToString(buffer1)}")

                    Console.WriteLine("Reading second section of a stream...")
                    Dim buffer2(10 - 1) As Byte
                    Dim bytesRead2 As Integer = stream.Read(buffer2, 0, buffer2.Length)
                    Console.WriteLine($"{bytesRead2} bytes read, buffer: {BitConverter.ToString(buffer2)}")

                    Console.WriteLine("Seeking...")
                    stream.Seek(100, SeekOrigin.Begin)

                    Console.WriteLine("Reading third section of a stream...")
                    Dim buffer3(20 - 1) As Byte
                    Dim bytesRead3 As Integer = stream.Read(buffer3, 0, buffer3.Length)
                    Console.WriteLine($"{bytesRead3} bytes read, buffer: {BitConverter.ToString(buffer3)}")
                End Using

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

The CreateStreamReader Method creates a "text reader" for reading text from a file; optionally, you can specify the encoding to be used.

The example below shows how to open a file stream for reading, and read its content using a text reader object, using OPC UA file provider model.

// Shows how to open a file stream for reading, and read its content using a text reader object, using OPC UA file provider
// model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using System.IO;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._FileInfo2
{
    class ReadText
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            UAEndpointDescriptor endpointDescriptor = "opc.tcp://localhost:48030";

            // A node that represents an instance of OPC UA FileType object.
            UANodeDescriptor fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile";
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting file info...");
            IFileInfo2 fileInfo2 = fileTransferClient.GetFileInfo2(endpointDescriptor, fileNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            try
            {
                // Get a stream reader object that corresponds to an OPC UA file.
                Console.WriteLine("Opening the file for reading...");

                // We know that the file contains text, so we read it using a stream reader. If the file content was
                // binary, you would process the stream according to the data format.
                using (StreamReader streamReader = fileInfo2.CreateStreamReader())
                {
                    // Read in the text from the file and display it line by line.
                    Console.WriteLine();
                    Console.WriteLine("Reading text lines:");

                    int i = 0;
                    while (!streamReader.EndOfStream)
                    {
                        string line = streamReader.ReadLine();
                        Console.WriteLine($"[{i}] {line}");
                        i++;
                    }
                }
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine();
            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to open a file stream for reading, and read its content using a text reader object, using OPC UA file provider
# model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

#requires -Version 5.1
using namespace System.IO
using namespace OpcLabs.BaseLib.Extensions.FileProviders
using namespace OpcLabs.EasyOpc.UA
using namespace OpcLabs.EasyOpc.UA.FileTransfer

# The path below assumes that the current directory is [ProductDir]/Examples-NET/PowerShell/Windows .
Add-Type -Path "../../../Components/Opclabs.QuickOpc/net472/OpcLabs.EasyOpcUA.dll"
Add-Type -Path "../../../Components/Opclabs.QuickOpc/net472/OpcLabs.EasyOpcUAComponents.dll"

# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
[UAEndpointDescriptor]$endpointDescriptor = "opc.tcp://localhost:48030"

# A node that represents an instance of OPC UA FileType object.
[UANodeDescriptor]$fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

# Instantiate the file transfer client object.
$fileTransferClient = New-Object EasyUAFileTransferClient

Write-Host "Getting file info..."
[IFileInfo2]$fileInfo2 = [IEasyUAFileTransferExtension]::GetFileInfo2($fileTransferClient, 
    $endpointDescriptor, $fileNodeDescriptor)
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

try {
    # Get a stream reader object that corresponds to an OPC UA file.
    Write-Host "Opening the file for reading..."

    # We know that the file contains text, so we read it using a stream reader. If the file content was
    # binary, you would process the stream according to the data format.
    try {
        [StreamReader]$streamReader = [IFileInfoExtension]::CreateStreamReader($fileInfo2)

        # Read in the text from the file and display it line by line.
        Write-Host 
        Write-Host "Reading text lines:"

        $i = 0
        while (-not $streamReader.EndOfStream) {
            $line = $streamReader.ReadLine()
            Write-Host "[$($i)] $($line)"
            $i++
        }
    }
    finally {
        if ($streamReader -ne $null) {
            $streamReader.Dispose()
        }
    }
}
# Methods in the file provider model throw IOException and other exceptions, but not UAException.
catch [Exception] {
    Write-Host "*** Failure: $($PSItem.Exception.GetBaseException().Message)"
    return
}

Write-Host 
Write-Host "Finished."
# Shows how to open a file stream for reading, and read its content using a text reader object, using OPC UA file provider
# model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from System.IO import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.FileTransfer import *
from OpcLabs.EasyOpc.UA.Navigation import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')

# A node that represents an instance of OPC UA FileType object.
fileNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile')

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

print('Getting file info......')
fileInfo2 = IEasyUAFileTransferExtension.GetFileInfo2(fileTransferClient,
                                                      endpointDescriptor,
                                                      UANamedNodeDescriptor(fileNodeDescriptor))
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Open the file, read two separate sections of it, and close it.
streamReader = None
try:
    # Get a stream reader object that corresponds to an OPC UA file.
    print('Opening the file for reading...')

    # We know that the file contains text, so we read it using a stream reader. If the file content was
    # binary, you would process the stream according to the data format.
    streamReader = IFileInfoExtension.CreateStreamReader(fileInfo2)

    # Read in the text from the file and display it line by line.
    print()
    print('Reading text lines...')
    i = 0
    while not streamReader.EndOfStream:
        line = streamReader.ReadLine()
        print('[', i, '] ', line, sep='')
        i = i + 1

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

finally:
    streamReader and streamReader.Dispose()

print()
print('Finished.')
' Shows how to open a file stream for reading, and read its content using a text reader object, using OPC UA file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports System.IO
Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._FileInfo2

    Friend Class ReadText

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor = "opc.tcp://localhost:48030"

            ' A node that represents an instance of OPC UA FileType object.
            Dim fileNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting file info...")
            Dim fileInfo2 As IFileInfo2 =
                fileTransferClient.GetFileInfo2(endpointDescriptor, fileNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            Try
                ' Get a stream reader object that corresponds to an OPC UA file.
                Console.WriteLine("Opening the file for reading...")

                ' We know that the file contains text, so we read it using a stream reader. If the file content was
                ' binary, you would process the stream according to the data format.
                Using streamReader As StreamReader = fileInfo2.CreateStreamReader()
                    ' Read in the text from the file and display it line by line.
                    Console.WriteLine()
                    Console.WriteLine("Reading text lines:")

                    Dim i As Integer = 0
                    While Not streamReader.EndOfStream
                        Dim line As String = streamReader.ReadLine()
                        Console.WriteLine($"[{i}] {line}")
                        i += 1
                    End While
                End Using

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine()
            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

In some cases, reading a file part by part is not needed, and you want to read the full file contents into memory. There extension methods like ReadAllBytes Method or ReadAllText Method that allow you to do that easily.

The example below shows how to read the full contents of an OPC UA file at once, using the file provider model.

// Shows how to read the full contents of an OPC UA file at once, using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using System.Text;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._FileInfo2
{
    class ReadAllBytes
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            UAEndpointDescriptor endpointDescriptor = "opc.tcp://localhost:48030";

            // A node that represents an instance of OPC UA FileType object.
            UANodeDescriptor fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile";
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting file info...");
            IFileInfo2 fileInfo2 = fileTransferClient.GetFileInfo2(endpointDescriptor, fileNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Read in all contents from a specified file node.
            byte[] bytes;
            try
            {
                Console.WriteLine("Reading the whole file...");
                bytes = fileInfo2.ReadAllBytes();
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            // Display result
            Console.WriteLine();
            // We know that the file contains text, so we convert the received data to a string. If the file contents was
            // binary, you would process the data according to their format.
            string text = Encoding.UTF8.GetString(bytes);
            Console.WriteLine("File content:");
            Console.WriteLine(text);

            Console.WriteLine();
            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to read the full contents of an OPC UA file at once, using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from System.Text import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.FileTransfer import *
from OpcLabs.EasyOpc.UA.Navigation import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')

# A node that represents an instance of OPC UA FileType object.
fileNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile')

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

print('Getting file info......')
fileInfo2 = IEasyUAFileTransferExtension.GetFileInfo2(fileTransferClient,
                                                      endpointDescriptor,
                                                      UANamedNodeDescriptor(fileNodeDescriptor))
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Read in all contents from a specified file node.
try:
    print('Reading the whole file...')
    bytes = IFileInfoExtension.ReadAllBytes(fileInfo2)

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

# Display result.
print()
# We know that the file contains text, so we convert the received data to a string. If the file contents was
# binary, you would process the data according to their format.
text = Encoding.UTF8.GetString(bytes)
print('File content:')
print(text)


print()
print('Finished.')
' Shows how to read the full contents of an OPC UA file at once, using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports System.Text
Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._FileInfo2

    Friend Class ReadAllBytes

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor = "opc.tcp://localhost:48030"

            ' A node that represents an instance of OPC UA FileType object.
            Dim fileNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting file info...")
            Dim fileInfo2 As IFileInfo2 =
                fileTransferClient.GetFileInfo2(endpointDescriptor, fileNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Read in all contents from a specified file node.
            Dim bytes As Byte()
            Try
                Console.WriteLine("Reading the whole file...")
                bytes = fileInfo2.ReadAllBytes()

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            ' Display result
            Console.WriteLine()
            ' We know that the file contains text, so we convert the received data to a string. If the file contents was
            ' binary, you would process the data according to their format.
            Dim text As String = Encoding.UTF8.GetString(bytes)
            Console.WriteLine("File content:")
            Console.WriteLine(text)

            Console.WriteLine()
            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

Writing

In order to write data to a file in the file provider model, start by calling the CreateWriteStream Method on the "file info" object. There are also extension methods (see CreateWriteStream Method) with different structure of input arguments. All these methods return a stream object that can subsequently be used to access the file data for writing or reading. Eventually, the stream object should be disposed of using the IDisposable.Dispose Method

The example below shows how to write data into a section of an OPC UA file, using the file provider model.

// Shows how to write data into a section of an OPC UA file, using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using System.IO;
using System.Text;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._WritableFileInfo
{
    class Write
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            UAEndpointDescriptor endpointDescriptor = "opc.tcp://localhost:48030";

            // A node that represents an instance of OPC UA FileType object.
            UANodeDescriptor fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile";
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting writable file info...");
            IWritableFileInfo writableFileInfo = fileTransferClient.GetWritableFileInfo(endpointDescriptor, fileNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Open the file, write a section of it, and close it.
            try
            {
                Console.WriteLine("Opening file...");
                using (Stream stream = writableFileInfo.CreateWriteStream(FileMode.Open, FileAccess.ReadWrite))
                {
                    Console.WriteLine("Writing file section...");
                    byte[] data = Encoding.UTF8.GetBytes("TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing a section of a file. <<<");
                    stream.Write(data, 0, data.Length);

                    Console.WriteLine("Closing file...");
                    // Disposing of the stream closes the file.
                }
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine();
            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to write data into a section of an OPC UA file, using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from System import *
from System.IO import *
from System.Text import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.FileTransfer import *
from OpcLabs.EasyOpc.UA.Navigation import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')

# A node that represents an OPC UA file system (a root directory).
fileNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile')

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

print('Getting writable file info...')
writableFileInfo = IEasyUAFileTransferExtension.GetWritableFileInfo(fileTransferClient,
                                                                    endpointDescriptor,
                                                                    UANamedNodeDescriptor(fileNodeDescriptor))
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Open the file, write a section of it, and close it.
stream = None
try:
    print('Opening file...')
    stream = writableFileInfo.CreateWriteStream(FileMode.Open, FileAccess.ReadWrite)

    print('Writing file section...')
    data = Encoding.UTF8.GetBytes('TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing a section of a file. '
                                  '<<<')
    stream.Write(data, 0, data.Length)

    print('Closing file...')
    # Disposing of the stream (in the 'finally' block) closes the file.

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

finally:
    stream and stream.Dispose()

print()
print('Finished.')
' Shows how to write data into a section of an OPC UA file, using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports System.IO
Imports System.Text
Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._WritableFileInfo

    Friend Class Write

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor = "opc.tcp://localhost:48030"

            ' A node that represents an instance of OPC UA FileType object.
            Dim fileNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting writable file info...")
            Dim writableFileInfo As IWritableFileInfo =
                fileTransferClient.GetWritableFileInfo(endpointDescriptor, fileNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Open the file, write a section of it, and close it.
            Try
                Console.WriteLine("Opening file...")
                Using stream As Stream = writableFileInfo.CreateWriteStream(FileMode.Open, FileAccess.ReadWrite)
                    Console.WriteLine("Writing file section...")
                    Dim data As Byte() = Encoding.UTF8.GetBytes("TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing a section of a file. <<<")
                    stream.Write(data, 0, data.Length)

                    Console.WriteLine("Closing file...")
                    ' Disposing of the stream closes the file.
                End Using

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine()
            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

In some cases, writing a file part by part is not needed, and you want to write the full file contents from what you already have in memory. There are extension methods like WriteAllBytes Method or WriteAllText Method that allow you to do that easily.

The example below shows how to write the full contents of an OPC UA file at once, using the file provider model.

// Shows how to write the full contents of an OPC UA file at once, using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using System.Text;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._WritableFileInfo
{
    class WriteAllBytes
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            UAEndpointDescriptor endpointDescriptor = "opc.tcp://localhost:48030";

            // A node that represents an instance of OPC UA FileType object.
            UANodeDescriptor fileNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile";
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting writable file info...");
            IWritableFileInfo writableFileInfo = fileTransferClient.GetWritableFileInfo(endpointDescriptor, fileNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Write all contents into a specified file node.
            byte[] bytes = Encoding.UTF8.GetBytes("TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing the whole contents of a file at once.");
            try
            {
                Console.WriteLine("Writing the whole file...");
                writableFileInfo.WriteAllBytes(bytes);

                // Due to an issue in the server, the file might not be readable now, without server restart.
                Console.WriteLine("Reading the data back...");
                byte[] data = writableFileInfo.ReadAllBytes();
                Console.WriteLine(Encoding.UTF8.GetString(data));
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine();
            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to write the full contents of an OPC UA file at once, using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from System import *
from System.Text import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.FileTransfer import *
from OpcLabs.EasyOpc.UA.Navigation import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')

# A node that represents an OPC UA file system (a root directory).
fileNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile')

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

print('Getting writable file info...')
writableFileInfo = IEasyUAFileTransferExtension.GetWritableFileInfo(fileTransferClient,
                                                                    endpointDescriptor,
                                                                    UANamedNodeDescriptor(fileNodeDescriptor))
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Write all contents into a specified file node.
bytes = Encoding.UTF8.GetBytes('TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing the whole contents of a '
                               'file at once.')
try:
    print('Writing the whole file...')
    IWritableFileInfoExtension.WriteAllBytes(writableFileInfo, bytes)

    # Due to an issue in the server, the file might not be readable now, without server restart.
    print('Reading the data back...')
    data = IFileInfoExtension.ReadAllBytes(writableFileInfo)
    print(Encoding.UTF8.GetString(data))

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

print()
print('Finished.')
' Shows how to write the full contents of an OPC UA file at once, using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports System.Text
Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._WritableFileInfo

    Friend Class WriteAllBytes

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor = "opc.tcp://localhost:48030"

            ' A node that represents an instance of OPC UA FileType object.
            Dim fileNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.TextFile"

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting writable file info...")
            Dim writableFileInfo As IWritableFileInfo =
                fileTransferClient.GetWritableFileInfo(endpointDescriptor, fileNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Write all contents into a specified file node.
            Dim bytes As Byte() = Encoding.UTF8.GetBytes("TEXT FROM FILE TRANSFER CLIENT EXAMPLE. Demonstrates writing the whole contents of a file at once.")
            Try
                Console.WriteLine("Writing the whole file...")
                writableFileInfo.WriteAllBytes(bytes)

                ' Due to an issue in the server, the file might Not be readable now, without server restart.
                Console.WriteLine("Reading the data back...")
                Dim data As Byte() = writableFileInfo.ReadAllBytes()
                Console.WriteLine(Encoding.UTF8.GetString(data))

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine()
            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

Other (extension) methods in this group, possibly not used in the above examples, include:

Loading and saving files

You can load the contents of any OPC UA file (in fact, any file in the file provider model) from a normal (operating system) file, using the LoadFromOSFile Method.

The contents of any OPC UA file (in fact, any file in the file provider model) can be saved to a normal (operating system) file using the SaveToOSFile Method.

Creating, deleting, copying and moving files and directories

Various methods on the "directory contents" and "file info" objects, and extensions methods on them, provide functionality for creating, deleting, copying and moving directories and files. The examples that follow show how the basic file system manipulations can be programmed.

The example below shows how to create and delete OPC UA files, using the file provider model.

// Shows how to create and delete OPC UA files, using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.Extensions;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._WritableFileInfo
{
    class CreateAndDelete
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            var endpointDescriptor = new UAEndpointDescriptor("opc.tcp://localhost:48030")
                .WithUserNameIdentity("john", "master");

            // A node that represents an OPC UA file system (a root directory).
            UANodeDescriptor fileSystemNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem";

            // Create a random number generator - will be used for file/directory names.
            var random = new Random();
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting writable file provider...");
            IWritableFileProvider writableFileProvider =
                fileTransferClient.GetWritableFileProvider(endpointDescriptor, fileSystemNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Create two files, and delete the first one.
            try
            {
                string fileName1 = "MyFile1-" + random.Next();
                Console.WriteLine($"Creating first file, '{fileName1}'...");
                IWritableFileInfo writableFileInfo1 = writableFileProvider.GetWritableFileInfo(fileName1);
                writableFileInfo1.WriteAllBytes(Array.Empty<byte>());

                string fileName2 = "MyFile2-" + random.Next();
                Console.WriteLine($"Creating second file, '{fileName2}'...");
                IWritableFileInfo writableFileInfo2 = writableFileProvider.GetWritableFileInfo(fileName2);
                writableFileInfo2.WriteAllBytes(Array.Empty<byte>());

                Console.WriteLine("Deleting the first file...");
                writableFileInfo1.Delete();
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to create and delete OPC UA files, using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc
import random

# Import .NET namespaces.
from System import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.Extensions import *
from OpcLabs.EasyOpc.UA.FileTransfer import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')
endpointDescriptor = UAEndpointDescriptorExtension.WithUserNameIdentity(endpointDescriptor,'john', 'master')

# A node that represents an OPC UA file system (a root directory).
fileSystemNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem')

# Create a random number generator - will be used for file/directory names.
random = random.Random()

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

# Prevent prompt to trust the server certificate (INSECURE, used just for smooth example flow).
EasyUAClient.SharedParameters.EngineParameters.CertificateAcceptancePolicy.TrustEndpointUrlString(
    endpointDescriptor.UrlString)

print('Getting writable file provider...')
writableFileProvider = IEasyUAFileTransferExtension.GetWritableFileProvider(fileTransferClient,
                                                                            endpointDescriptor,
                                                                            fileSystemNodeDescriptor)
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Create two files, and delete the first one.
try:
    fileName1 = 'MyFile1-' + str(random.randint(0, 999_999_999))
    print("Creating first file, '", fileName1, "'...", sep='')
    writableFileInfo1 = writableFileProvider.GetWritableFileInfo(fileName1)
    IWritableFileInfoExtension.WriteAllBytes(writableFileInfo1, Array.Empty[Byte]())

    fileName2 = 'MyFile2-' + str(random.randint(0, 999_999_999))
    print("Creating second file, '", fileName2, "'...", sep='')
    writableFileInfo2 = writableFileProvider.GetWritableFileInfo(fileName2)
    IWritableFileInfoExtension.WriteAllBytes(writableFileInfo2, Array.Empty[Byte]())

    print('Deleting the first file...')
    writableFileInfo1.Delete()

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

print()
print('Finished.')
' Shows how to create and delete OPC UA files, using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.Extensions
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._WritableFileInfo

    Friend Class CreateAndDelete

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor =
                New UAEndpointDescriptor("opc.tcp://localhost:48030") _
                .WithUserNameIdentity("john", "master")

            ' A node that represents an OPC UA file system (a root directory).
            Dim fileSystemNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem"

            ' Create a random number generator - will be used for file/directory names.
            Dim random = New Random

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting writable file provider...")
            Dim writableFileProvider As IWritableFileProvider =
                fileTransferClient.GetWritableFileProvider(endpointDescriptor, fileSystemNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Create two files, and delete the first one.
            Try
                Dim fileName1 As String = "MyFile1-" & random.Next()
                Console.WriteLine($"Creating first file, '{fileName1}'...")
                Dim writableFileInfo1 As IWritableFileInfo = writableFileProvider.GetWritableFileInfo(fileName1)
                writableFileInfo1.WriteAllBytes(Array.Empty(Of Byte))

                Dim fileName2 As String = "MyFile2-" & random.Next()
                Console.WriteLine($"Creating second file, '{fileName2}'...")
                Dim writableFileInfo2 As IWritableFileInfo = writableFileProvider.GetWritableFileInfo(fileName2)
                writableFileInfo2.WriteAllBytes(Array.Empty(Of Byte))

                Console.WriteLine("Deleting the first file...")
                writableFileInfo1.Delete()

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

The example below shows how to create and delete OPC UA directories, using the file provider model.

// Shows how to create and delete OPC UA directories, using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.Extensions;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._WritableDirectoryContents
{
    class CreateAndDelete
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            var endpointDescriptor = new UAEndpointDescriptor("opc.tcp://localhost:48030")
                .WithUserNameIdentity("john", "master");

            // A node that represents an OPC UA file system (a root directory).
            UANodeDescriptor fileSystemNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem";

            // Create a random number generator - will be used for file/directory names.
            var random = new Random();
            
            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting writable file provider...");
            IWritableFileProvider writableFileProvider =
                fileTransferClient.GetWritableFileProvider(endpointDescriptor, fileSystemNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Create two directories, and one nested directory, and delete the first one.
            try
            {
                string directoryName1 = "MyDirectory1-" + random.Next();
                Console.WriteLine($"Creating first directory, '{directoryName1}'...");
                IWritableDirectoryContents writableDirectoryContents1 = writableFileProvider.GetWritableDirectoryContents(directoryName1);
                writableDirectoryContents1.Create();

                string directoryName2 = "MyDirectory2-" + random.Next();
                Console.WriteLine($"Creating second directory, '{directoryName2}'...");
                IWritableDirectoryContents writableDirectoryContents2 = writableFileProvider.GetWritableDirectoryContents(directoryName2);
                writableDirectoryContents2.Create();

                string nestedDirectoryName = "MyDirectory3-" + random.Next();
                Console.WriteLine($"Creating nested directory, '{nestedDirectoryName}'...");
                writableDirectoryContents2.CreateSubdirectory(nestedDirectoryName);

                // At this moment, the directory structure we have created looks like this:
                // * MyDirectory1
                // * MyDirectory2
                // * * MyDirectory3

                Console.WriteLine("Deleting the first directory...");
                writableDirectoryContents1.Delete();
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to create and delete OPC UA directories, using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc
import random

# Import .NET namespaces.
from System import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.Extensions import *
from OpcLabs.EasyOpc.UA.FileTransfer import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')
endpointDescriptor = UAEndpointDescriptorExtension.WithUserNameIdentity(endpointDescriptor,'john', 'master')

# A node that represents an OPC UA file system (a root directory).
fileSystemNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem')

# Create a random number generator - will be used for file/directory names.
random = random.Random()

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

# Prevent prompt to trust the server certificate (INSECURE, used just for smooth example flow).
EasyUAClient.SharedParameters.EngineParameters.CertificateAcceptancePolicy.TrustEndpointUrlString(
    endpointDescriptor.UrlString)

print('Getting writable file provider...')
writableFileProvider = IEasyUAFileTransferExtension.GetWritableFileProvider(fileTransferClient,
                                                                            endpointDescriptor,
                                                                            fileSystemNodeDescriptor)
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Create two directories, and one nested directory, and delete the first one.
try:
    directoryName1 = 'MyDirectory1-' + str(random.randint(0, 999_999_999))
    print("Creating first directory, '", directoryName1, "'...", sep='')
    writableDirectoryContents1 = writableFileProvider.GetWritableDirectoryContents(directoryName1)
    writableDirectoryContents1.Create()

    directoryName2 = 'MyDirectory2-' + str(random.randint(0, 999_999_999))
    print("Creating second directory, '", directoryName2, "'...", sep='')
    writableDirectoryContents2 = writableFileProvider.GetWritableDirectoryContents(directoryName2)
    writableDirectoryContents2.Create()

    nestedDirectoryName = 'MyDirectory3-' + str(random.randint(0, 999_999_999))
    print("Creating nested directory, '", nestedDirectoryName, "'...", sep='')
    IWritableDirectoryContentsExtension.CreateSubdirectory(writableDirectoryContents2, nestedDirectoryName)

    # At this moment, the directory structure we have created looks like this:
    # * MyDirectory1
    # * MyDirectory2
    # * * MyDirectory3

    print('Deleting the first directory...')
    IWritableDirectoryContentsExtension.Delete(writableDirectoryContents1)

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

print()
print('Finished.')
' Shows how to create and delete OPC UA directories, using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.Extensions
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._WritableDirectoryContents

    Friend Class CreateAndDelete

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor =
                New UAEndpointDescriptor("opc.tcp://localhost:48030") _
                .WithUserNameIdentity("john", "master")

            ' A node that represents an OPC UA file system (a root directory).
            Dim fileSystemNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem"

            ' Create a random number generator - will be used for file/directory names.
            Dim random = New Random

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting writable file provider...")
            Dim writableFileProvider As IWritableFileProvider =
                fileTransferClient.GetWritableFileProvider(endpointDescriptor, fileSystemNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Create two directories, and one nested directory, and delete the first one.
            Try
                Dim directoryName1 As String = "MyDirectory1-" & random.Next()
                Console.WriteLine($"Creating first directory, '{directoryName1}'...")
                Dim writableDirectoryContents1 As IWritableDirectoryContents = writableFileProvider.GetWritableDirectoryContents(directoryName1)
                writableDirectoryContents1.Create()

                Dim directoryName2 As String = "directoryName2-" & random.Next()
                Console.WriteLine($"Creating second directory, '{directoryName2}'...")
                Dim writableDirectoryContents2 As IWritableDirectoryContents = writableFileProvider.GetWritableDirectoryContents(directoryName2)
                writableDirectoryContents2.Create()

                Dim nestedDirectoryName As String = "MyDirectory3-" & random.Next()
                Console.WriteLine($"Creating nested directory, '{nestedDirectoryName}'...")
                writableDirectoryContents2.CreateSubdirectory(nestedDirectoryName)

                ' At this moment, the directory structure we have created looks Like this
                ' * MyDirectory1
                ' * MyDirectory2
                ' * * MyDirectory3

                Console.WriteLine("Deleting the first directory...")
                writableDirectoryContents1.Delete()

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

The example below shows how to copy an OPC UA file, using the file provider model.

// Shows how to copy an OPC UA file, using the file provider model.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

using System;
using OpcLabs.BaseLib.Extensions.FileProviders;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.Extensions;
using OpcLabs.EasyOpc.UA.FileTransfer;

namespace UADocExamples.FileProviders._WritableFileInfo
{
    class CopyTo
    {
        public static void Main1()
        {
            // Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            var endpointDescriptor = new UAEndpointDescriptor("opc.tcp://localhost:48030")
                .WithUserNameIdentity("john", "master");

            // A node that represents an OPC UA file system (a root directory).
            UANodeDescriptor fileSystemNodeDescriptor = "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem";

            // Create a random number generator - will be used for file/directory names.
            var random = new Random();

            // Instantiate the file transfer client object
            var fileTransferClient = new EasyUAFileTransferClient();

            Console.WriteLine("Getting writable file provider...");
            IWritableFileProvider writableFileProvider =
                fileTransferClient.GetWritableFileProvider(endpointDescriptor, fileSystemNodeDescriptor);
            // From this point onwards, the code is independent of the concrete realization of the file provider, and would
            // be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            // Create a file, and a directory. Then, copy the file into the directory.
            try
            {
                string fileName = "MyFile-" + random.Next();
                Console.WriteLine($"Creating file, '{fileName}'...");
                IWritableFileInfo writableFileInfo = writableFileProvider.GetWritableFileInfo(fileName);
                writableFileInfo.WriteAllBytes(Array.Empty<byte>());

                string directoryName = "MyDirectory-" + random.Next();
                Console.WriteLine($"Creating directory, '{directoryName}'...");
                IWritableDirectoryContents writableDirectoryContents = writableFileProvider.GetWritableDirectoryContents(directoryName);
                writableDirectoryContents.Create();

                Console.WriteLine("Copying the file...");
                writableFileInfo.CopyTo(FormattableString.Invariant($"{directoryName}/{fileName}"));
            }
            // Methods in the file provider model throw IOException and other exceptions, but not UAException.
            catch (Exception exception)
            {
                Console.WriteLine($"*** Failure: {exception.GetBaseException().Message}");
                return;
            }

            Console.WriteLine("Finished...");
        }
    }
}
# Shows how to copy an OPC UA file, using the file provider model.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc
import random

# Import .NET namespaces.
from System import *
from OpcLabs.BaseLib.Extensions.FileProviders import *
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.Extensions import *
from OpcLabs.EasyOpc.UA.FileTransfer import *


# Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe).
endpointDescriptor = UAEndpointDescriptor('opc.tcp://localhost:48030')
endpointDescriptor = UAEndpointDescriptorExtension.WithUserNameIdentity(endpointDescriptor,'john', 'master')

# A node that represents an OPC UA file system (a root directory).
fileSystemNodeDescriptor = UANodeDescriptor('nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem')

# Create a random number generator - will be used for file/directory names.
random = random.Random()

# Instantiate the file transfer client object.
fileTransferClient = EasyUAFileTransferClient()

# Prevent prompt to trust the server certificate (INSECURE, used just for smooth example flow).
EasyUAClient.SharedParameters.EngineParameters.CertificateAcceptancePolicy.TrustEndpointUrlString(
    endpointDescriptor.UrlString)

print('Getting writable file provider...')
writableFileProvider = IEasyUAFileTransferExtension.GetWritableFileProvider(fileTransferClient,
                                                                            endpointDescriptor,
                                                                            fileSystemNodeDescriptor)
# From this point onwards, the code is independent of the concrete realization of the file provider, and would
# be identical e.g. for files in the physical file system, if the corresponding file provider was used.

# Create a file, and a directory. Then, copy the file into the directory.
try:
    fileName = 'MyFile-' + str(random.randint(0, 999_999_999))
    print("Creating file, '", fileName, "'...", sep='')
    writableFileInfo = writableFileProvider.GetWritableFileInfo(fileName)
    IWritableFileInfoExtension.WriteAllBytes(writableFileInfo, Array.Empty[Byte]())

    directoryName = 'MyDirectory-' + str(random.randint(0, 999_999_999))
    print("Creating  directory, '", directoryName, "'...", sep='')
    writableDirectoryContents = writableFileProvider.GetWritableDirectoryContents(directoryName)
    writableDirectoryContents.Create()

    print('Copying the file...')
    IWritableFileInfoExtension.CopyTo(writableFileInfo, directoryName + '/' + fileName)

# Methods in the file provider model throw IOException and other exceptions, but not UAException.
except Exception as exception:
    print('*** Failure: ' + exception.GetBaseException().Message)
    exit()

print()
print('Finished.')
' Shows how to copy an OPC UA file, using the file provider model.
'
' Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .

Imports OpcLabs.BaseLib.Extensions.FileProviders
Imports OpcLabs.EasyOpc.UA
Imports OpcLabs.EasyOpc.UA.Extensions
Imports OpcLabs.EasyOpc.UA.FileTransfer

Namespace FileProviders._WritableFileInfo

    Friend Class CopyTo

        Public Shared Sub Main1()

            ' Unified Automation .NET based demo server (UaNETServer/UaServerNET.exe)
            Dim endpointDescriptor As UAEndpointDescriptor =
                New UAEndpointDescriptor("opc.tcp://localhost:48030") _
                .WithUserNameIdentity("john", "master")

            ' A node that represents an OPC UA file system (a root directory).
            Dim fileSystemNodeDescriptor As UANodeDescriptor =
                "nsu=http://www.unifiedautomation.com/DemoServer/ ;s=Demo.Files.FileSystem"

            ' Create a random number generator - will be used for file/directory names.
            Dim random = New Random

            ' Instantiate the file transfer client object
            Dim fileTransferClient = New EasyUAFileTransferClient

            Console.WriteLine("Getting writable file provider...")
            Dim writableFileProvider As IWritableFileProvider =
                fileTransferClient.GetWritableFileProvider(endpointDescriptor, fileSystemNodeDescriptor)
            ' From this point onwards, the code is independent of the concrete realization of the file provider, and would
            ' be identical e.g. for files in the physical file system, if the corresponding file provider was used.

            ' Create a file, and a directory. Then, copy the file into the directory.
            Try
                Dim fileName As String = "MyFile-" & random.Next()
                Console.WriteLine($"Creating file, '{fileName}'...")
                Dim writableFileInfo As IWritableFileInfo = writableFileProvider.GetWritableFileInfo(fileName)
                writableFileInfo.WriteAllBytes(Array.Empty(Of Byte))

                Dim directoryName As String = "MyDirectory-" & random.Next()
                Console.WriteLine($"Creating directory, '{directoryName}'...")
                Dim writableDirectoryContents As IWritableDirectoryContents = writableFileProvider.GetWritableDirectoryContents(directoryName)
                writableDirectoryContents.Create()

                Console.WriteLine("Copying the file...")
                writableFileInfo.CopyTo(FormattableString.Invariant($"{directoryName}/{fileName}"))

                ' Methods in the file provider model throw IOException and other exceptions, but not UAException.
            Catch exception As Exception
                Console.WriteLine("*** Failure: {0}", exception.GetBaseException.Message)
                Exit Sub
            End Try

            Console.WriteLine("Finished...")
        End Sub
    End Class
End Namespace

 

Other (extension) methods in this group, possibly not used in the above examples, include:

Loading and saving directories

You can load the contents of any OPC UA directory (in fact, any directory in the file provider model) from a physical directory (this includes all files and sub-directories, recursively), using the LoadFromOSDirectory Method.

The contents of any OPC UA directory (in fact, any directory in the file provider model), including all files and sub-directories, can be saved to a physical directory using the SaveToOSDirectory Method.

See Also

Examples - OPC UA File Providers

Knowledge Base